const Router = require('koa-router')
const { error, INFO } = require('./utils/error')
const apiError = (info) => {
  error('50000', __filename, info)
}
const { requestAuthorInfo, requestAuthorDynamic } = require('./api/author')
const router = new Router({
  prefix: '/api/author'
})
router.get('/', async (ctx) => {
  const { id, userId } = ctx.query
  let result
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestAuthorInfo({
      id,
      opId: userId
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 1
        const item = data.data
        result = {
          id: item.userId,
          name: item.userName,
          imgUrl: item.userImg,
          follow: item.followNumber,
          fans: item.fansNumber,
          attention: item.isFollow === 1
        }
      } else {
        code = -1
        msg = data.msg
      }
    }
  } catch (error) {
    code = -1
    apiError('GET-/')
    msg = INFO['50000']
  }
  ctx.body = {
    code,
    data: result,
    msg
  }
})
router.get('/dynamic', async (ctx) => {
  const { page, limit, id } = ctx.query
  let result = {}
  let code = -1
  let msg = ''
  try {
    const { status, data } = await requestAuthorDynamic({
      id,
      curr: page,
      limit
    })
    if (status === 200) {
      if (data.statu === 0) {
        code = 1
        result = data.data
          .filter((_, index) => {
            return index < limit
          })
          .map((item) => {
            return {
              id: item.id,
              title: item.title,
              imgUrl: item.img,
              classId: item.plateId,
              mapId: item.classId,
              time: item.date,
              author: {
                name: item.authorName,
                id: item.authorId
              },
              browse: item.browse,
              comments: item.comments,
              content: item.content
            }
          })
      } else if (data.statu === 1) {
        code = 0
        msg = data.msg
      }
    }
  } catch (error) {
    apiError('GET-dynamic')
    msg = INFO['50000']
  } finally {
    ctx.body = {
      code,
      data: result,
      msg
    }
  }
})
module.exports = router
